//
//  ExamineManager.m
//  gdemm
//
//  Created by 乔明超 on 16/10/26.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "ExamineManager.h"
#import "ExamineActionListener.h"
#import "FileUtil.h"
#import "ApiSupport.h"
#import "RootChecker.h"
#import "PackagesChecker.h"
#import "WLANChecker.h"
#import "MobileConfigChecker.h"
#import "DeviceInfo.h"
#import "TimeUtil.h"
#import "KeyChain.h"
@interface ExamineManager()
@property (assign,nonatomic) BOOL isBreak;
@property (strong,nonatomic)  NSMutableArray<ExamineItem *> *mExamineItems;
@property (strong,nonatomic)  NSMutableArray <ExamineItem *> *mFailedItems;

@end
@implementation ExamineManager
static ExamineManager *_instance;

- (instancetype)init
{
    self = [super init];
    if (self) {
//        [self startExamine];
    }
    return self;
}
//获取PolicyManager单例,在app登录之后加载该单例
+ (instancetype)getInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc]init];
    });
    return _instance;
    
}

/**
 *  懒加载
 */

//保存检测结果
- (NSMutableDictionary *)examineResult{
    if (_examineResult == nil) {
        _examineResult = [NSMutableDictionary dictionary];
    }
    return _examineResult;
}

//保存检测成功的检测项
- ( NSMutableArray<ExamineItem *> *)mExamineItems{
    if (_mExamineItems == nil) {
        _mExamineItems = [NSMutableArray array];
    }
    return _mExamineItems;
}


//保存检测失败的检测项
- (NSArray<ExamineItem *> *)mFailedItems{
    if (_mFailedItems == nil) {
        _mFailedItems = [ NSMutableArray array];
    }
    return _mFailedItems;
}

- (void)addExamineItem:(ExamineItem *)item{
     // 每一次检测完以后不清空，下一次检测还会取上一次的检测项，导致已经删除的检测项还会被检测。
    if (_mIsExamineItemAdded) {
        [self.mExamineItems removeAllObjects];
    }
    if (![self.mExamineItems containsObject:item]) {
        item.mActionListener = _mActListener;
        [self.mExamineItems addObject:item];
    }
    _mIsExamineItemAdded = NO;

}

- (void)addExamineItem:(ExamineItem *)item withLocation:(NSInteger)location{
    // 每一次检测完以后不清空，下一次检测还会取上一次的检测项，导致已经删除的检测项还会被检测。
    if (_mIsExamineItemAdded) {
        [self.mExamineItems removeAllObjects];
    }
    if (![self.mExamineItems containsObject:item]) {
        item.mActionListener = _mActListener;
        [self.mExamineItems insertObject:item atIndex:location];
    }
    _mIsExamineItemAdded = NO;
}

/**
 * 获取检测规则文件
 */

- (NSString *)getExamineFile{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *dir = [paths[0] stringByAppendingPathComponent:@"config"];
    if (![FileUtil mkdirWithPath:dir]) {
        HRLog(@"make policy dir failed%@",dir);
        return nil;
    }
    return [dir stringByAppendingPathComponent:EXAMINE_FILE_NAME_TAG];
}

/**
 * 下载检测规则
 */
- (BOOL)downloadExamine{
    NSString *examineUrl = [ApiSupport getExamineUrl];
    if (examineUrl == nil) {
        HRLog(@"the examineUrl is  nil");
        
    }else{
        HRLog(@"the examineUrl is not nil:%@",examineUrl);
        NSString *tmpExamineFile  = [self getExamineFile];
        if (tmpExamineFile != nil) {
            tmpExamineFile = [tmpExamineFile stringByAppendingString:@".tmp"];
            
            if (![HttpUtil downloadTofileWithUrl:examineUrl withFileName:tmpExamineFile]) {
                HRLog(@"download examine file failed");
            }else{
                NSFileManager *fileMgr = [NSFileManager defaultManager];
                if ([fileMgr fileExistsAtPath:tmpExamineFile]) {
                    NSString *origin = [self getExamineFile];
                    [fileMgr removeItemAtPath:origin error:nil];
                    [fileMgr moveItemAtPath:tmpExamineFile toPath:origin error:nil];
                    return YES;
                }
            }
        }
        
    
    }
    
    return NO;
}

/**
 *  开始安全检测
 */

- (void)startExamine{

    //防止多个线程同时检测
    @synchronized (self) {
        if (_mIsExamining) {
            return;
        }
        [[ExamineManager getInstance].examineResult removeAllObjects];
        [[WLANChecker getInstance] reset];
        [[PackagesChecker getInstance]reset];
        [[MobileConfigChecker getInstance]reset];
        [self.mExamineItems removeAllObjects];
        _mIsExamining = YES;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self.mFailedItems removeAllObjects];
            if (![self downloadExamine]) {
                HRLog(@"download examine file failed");
            }
            [self startExamingReally];
            
        });
    }
}


/**
 *  开始检测
 */
- (void)startExamingReally{

    [self loadExamineItems];

    if (self.mExamineItems.count == 0) {
        if (self.mActListener != nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.mActListener onExamineUpdateUI];
            });
            
        }
        _mIsExamining = NO;
        return;
    }
    if (self.mActListener != nil) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.mActListener onExamineStart];
        });
        
    }
    
    BOOL success = YES;
    for (ExamineItem *item in self.mExamineItems) {
        
        if (![item examine]) {
            success = NO;
            [self.mFailedItems addObject:item];
        }
    }
    
    if (_isBreak) {
        success = NO;
    }
    
    if (self.mActListener != nil) {
        HRLog(@"examine finished -----------%ld",self.mExamineItems.count);
        [self.mActListener onExamineFinish:success];
    }
    
    _mIsExamining = NO;
    BOOL isSuccess = [self sumbitExamineInfo:self.examineResult];
    if (isSuccess) {
        HRLog(@"the examine info submit success");
    }else{
        HRLog(@"the examine info submit failed");
    }
    _mIsExamineItemAdded = YES;
    
}


/**
 *  获取总的检测项数目
 */
- (NSInteger)getTotalExamineCount{
    NSInteger count = 0;
    for (ExamineItem *item in self.mExamineItems ) {
        count += [item getExamineContentCount];
    }
    return count;
}

/**
 *  加载检测项
 */
- (void)loadExamineItems{
    NSString *examineFile = [self getExamineFile];
    if (examineFile != nil && [FileUtil isFileExistWithFilePath:examineFile]) {
        NSDictionary *examines = [NSDictionary dictionaryWithContentsOfFile:examineFile];
        HRLog(@"examines = %@",examines);
        [examines enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            NSString *type = (NSString *)key;
            if ([type isEqualToString:CHECK_ROOT]) {
                //添加Root检测项
                [self addExamineItem:[RootChecker getInstance]];
                _mIsRootChecked = YES;
            }else if ([type isEqualToString:CHECK_MOBILECONFIG]){
                //添加描述文件检测
                [self addExamineItem:[MobileConfigChecker getInstance]];
                _mIsMobileConfigChecked = YES;
                
            }else if ([type isEqualToString:DEVOPTION_TAG]){
            
            }else if ([type isEqualToString:CHECK_PACKAGES]){
                //添加package检测项
                [[PackagesChecker getInstance] getExamineContent:obj[@"content"]];
                [self addExamineItem:[PackagesChecker getInstance]];
                _mIsPackageChecked = YES;
            
            }else if ([type isEqualToString:CHECK_WLAN]){
                [[WLANChecker getInstance]getExamineContent:obj[@"content"]];
                [self addExamineItem:[WLANChecker getInstance]];
                _mIsWlanChecked = YES;
            
            }else if ([type isEqualToString:@"checkConnect"]){
                
            }
            
        }];
    }
    HRLog(@" = %@",self.examineResult);
}

- (NSMutableArray<ExamineItem *> *)getFailedItems{
    return self.mFailedItems;
}


/**
 测评结果信息构建json数据

 @param examineResult 测评结果
 @return
 */
- (NSMutableDictionary *)buildExamineInfo:(NSMutableDictionary *)examineResult{

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    [dict setValue:[[UserDefaultsUtil shareInstance]getString:LC_USERGUID ] forKey:@"userGUID"];
    
    [dict setValue:[KeyChain getUDID] forKey:@"deviceId"];
    
    [dict setValue:[TimeUtil currentTime] forKey:@"checkTime"];
    NSMutableArray *itemsArr = [NSMutableArray array];
    [examineResult enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSMutableDictionary *itemDict = [NSMutableDictionary dictionary];
        
        [itemDict setValue:key forKey:@"checkItem"];
        if ([obj isKindOfClass:[NSString class]]) {
            [itemDict setValue:obj forKey:@"illegalInfo"];
            [itemDict setValue:@1 forKey:@"illegal"];
        }else{
            [itemDict setValue:key forKey:@"legalInfo"];
            [itemDict setValue:@0 forKey:@"illegal"];
            
        }
        HRLog(@"examine---- %@:%@",key,obj);
        [itemsArr addObject:itemDict];
    }];
    
    [dict setValue:itemsArr forKey:@"checkRs"];
    HRLog(@"the sumbit string is :%@",dict);
    
    return dict;
    
}


/**
 测评结果提交

 @param info 测评结果数据
 @return 
 */
- (BOOL)sumbitExamineInfo :(NSMutableDictionary *)info{

    NSDictionary *infoDic = [self buildExamineInfo:info];
    NSString *submitUrl = [ApiSupport submitSafeCheckInfoUrl];
    if (submitUrl != nil) {
        NSDictionary *jsonDict = [HttpUtil postWithUrl:submitUrl withDict:infoDic withType:@"checkData"];
        if (jsonDict != nil) {
            NSString *result = jsonDict[@"result"];
            if ([result isEqualToString:@"failed"]) {
                return NO;
            }else{
                return YES;
            }
            
        }
    }
    
    return NO;
}
@end
